﻿using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace eslib.NetUpdator
{
    /// <summary>
    /// 在线更新器
    /// </summary>
    public class OnlineUpdator
    {
        UpdatorConfig config { get; set; }

        public OnlineUpdator(UpdatorConfig config)
        {
            this.config = config;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="targetVersionJsonWebUrl">目标版本Json配置web路径</param>
        public OnlineUpdator(string targetVersionJsonWebUrl)
        {
            try
            {
                var (success, result) = NetDownloader.GetNetText(targetVersionJsonWebUrl).Result;
                if (success)
                {
                    //目标更新配置
                    config = UpdatorConfig.LoadFromJson(result);
                }
                else
                {
                    throw new Exception("下载更新配置文件时失败");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"从web路径中获取目标版本Json配置文件时异常：{ex.Message}");
            }

            if (config == null)
            {
                throw new Exception($"目标版本Json配置异常,不能为null");
            }
        }




        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="log">日志输出回callback</param>
        /// <returns></returns>
        public async Task<bool> Update(UpdateMessageDelegate log)
        {
            //更新检查 
            if (!NeedUpdate())
            {
                log("巳是最新版本");
                return true;
            }

            //更新版本
            log($"正在更新{config.VersionName}(Version:{config.Version})");

            //下载zip
            (bool success, byte[] result) res = await NetDownloader.Download(config.ZipFileUrl);
            if (res.success)
            {
                log("zip更新包下载完成");
                string extra = config.ExtraDirFullPath();     //完整目标路径

                //解压到目录
                if (!Directory.Exists(extra))
                {
                    Directory.CreateDirectory(extra);
                    log($"创建目录{extra}");
                }

                string zip = Path.Combine(extra, Path.GetFileName(config.ZipFileUrl));
                try
                {
                    File.WriteAllBytes(zip, res.result);
                    log($"zip保存到{zip}");
                }
                catch (Exception ex)
                {
                    log($"保存zip文件异常:{ex.Message}");
                    return false;
                }

                try
                {
                    //解压到本地
                    ZipFile.ExtractToDirectory(zip, extra, true);     //覆盖更新

                    //更新本地配置文件
                    UpdatorConfig.Update(config);
                    log("巳更新本地updator配置");

                    //删除zip
                    File.Delete(zip);
                    log("zip解压完成，成功完成更新");

                }
                catch (Exception ex)
                {
                    log($"解压zip文件异常:{ex.Message}");
                    return false;
                }

                return true;
            }
            else
            {
                log("下载zip文件失败");
                return false;
            }
        }


        /// <summary>
        /// 检查是否需要更新，需要更新返回true
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool NeedUpdate()
            => UpdatorConfig.Local.NeedUpdate(config);

    }

    public delegate void UpdateMessageDelegate(string msg);
}
